package com.intelligence.medical.config;

import com.intelligence.medical.store.MongoChatMemoryStore;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Configuration
public class AgentConfig {
    @Autowired
    private MongoChatMemoryStore mongoChatMemoryStore;

    @Bean
    public ChatMemoryProvider chatMemoryProvider(){

      return memoryId ->
          MessageWindowChatMemory.builder()
                  .id(memoryId)
                  .maxMessages(20)
                  .chatMemoryStore(mongoChatMemoryStore)
                  .build();
    }

    @Bean
    ContentRetriever contentRetriever() {
        // Use the FileSystemDocumentLoader to read the knowledge base documents in the specified directory.
        // And use the default document parser to parse the document.
        Document document1 = FileSystemDocumentLoader.loadDocument("knowledge\\HospitalInformation.md");
        Document document2 = FileSystemDocumentLoader.loadDocument("knowledge\\DepartmentInformation.md");
        Document document3 = FileSystemDocumentLoader.loadDocument("knowledge\\NeurologyDepartment.md");
        Document document4 = FileSystemDocumentLoader.loadDocument("knowledge\\DentalDepartment.md");
        List<Document> documents = Arrays.asList(document1, document2, document3, document4);

        // Use in-memory vector storage
        InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
        // Use the default document splitter
        EmbeddingStoreIngestor.ingest(documents, embeddingStore);

        // Retrieve information relevant to the query content from the EmbeddingStore
        return EmbeddingStoreContentRetriever.from(embeddingStore);

    }
}
